﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Ongoal.Quotation.Service;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Ongoal.Quotation.APIExtensions
{
    /// <summary>
    /// 
    /// </summary>
    public static class HostBuilderExtensions
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static IHostBuilder UseAutofac(this IHostBuilder builder)
        {
            builder.UseServiceProviderFactory(new AutofacServiceProviderFactory());
            var hostBuilder = builder.ConfigureContainer<ContainerBuilder>(builder =>
            {
                try
                {
                    List<Assembly> assemblys = new List<Assembly>();
                    var binPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); 
                    var dllList = Directory.GetFiles(binPath, "Ongoal.*.dll");
                    if (dllList != null && dllList.Count() > 0)
                    {
                        var baseType = typeof(IServiceBase);
                        foreach (var dll in dllList)
                        {
                            assemblys.Add(Assembly.LoadFrom(dll));
                        }
                        //assemblys.Add(Assembly.GetEntryAssembly());
                        builder.RegisterAssemblyTypes(assemblys.ToArray()).Where(t => baseType.IsAssignableFrom(t) && t != baseType).AsImplementedInterfaces().InstancePerLifetimeScope();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message + "\n" + ex.InnerException);
                }
            });
            return builder;
        }
    }
}
